import React from "react";
import ReactDOM from "react-dom";
import "./index.css";

function Square(props) {
  const { onClick, colored } = props;
  return (
    <button
      className="square"
      onClick={onClick}
      style={{ backgroundColor: colored ? "yellow" : "" }}
    >
      {props.value}
    </button>
  );
}

class Board extends React.Component {
  renderSquare(i) {
    const { winnerSquares, squares, onClick } = this.props;
    return (
      <Square
        value={squares[i]}
        onClick={() => onClick(i)}
        key={i}
        colored={winnerSquares.indexOf(i) > -1 ? true : false}
      />
    );
  }

  renderCheckerboard = (numbers) =>
    numbers.map((item, index) => {
      if (Array.isArray(item)) {
        return (
          <div key={index} className="board-row">
            {this.renderCheckerboard(item)}
          </div>
        );
      } else {
        return this.renderSquare(item);
      }
    });

  render() {
    const numbers = [
      [0, 1, 2],
      [3, 4, 5],
      [6, 7, 8],
    ];
    return <div>{this.renderCheckerboard(numbers)}</div>;
  }
}

class Game extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      history: [
        {
          squares: Array(9).fill(null),
          coordinate: [0, 0],
        },
      ],
      xIsNext: true,
      stepNumber: 0,
      ascend: true,
    };
  }

  handleClick(i) {
    const history = this.state.history.slice(0, this.state.stepNumber + 1);
    const current = history[history.length - 1];
    const squares = current.squares.slice();
    if (calculateWinner(squares).length > 0 || squares[i]) {
      return;
    }
    squares[i] = this.state.xIsNext ? "X" : "O";
    this.setState({
      history: history.concat([
        { squares: squares, coordinate: [Math.floor(i / 3) + 1, (i % 3) + 1] },
      ]),
      stepNumber: history.length,
      xIsNext: !this.state.xIsNext,
    });
  }

  jumpTo(step) {
    this.setState({
      stepNumber: step,
      xIsNext: step % 2 === 0,
    });
  }

  // 排序
  sort() {
    const { ascend } = this.state;
    this.setState({
      ascend: !ascend,
    });
  }

  render() {
    const { stepNumber, ascend, history } = this.state;
    const current = history[this.state.stepNumber];
    const winnerSquares = calculateWinner(current.squares);
    let winner = "";
    if (winnerSquares.length > 0) {
      winner = current.squares[winnerSquares[0]];
    }
    // if (!winner && stepNumber > 8) {
    //   alert("平局");
    // }

    const moves = history.map((step, move) => {
      let desc = move ? "go to move #" + move : "go to game start";
      if (move > 0) {
        desc += ", (" + step.coordinate[1] + ", " + step.coordinate[0] + ")";
      }
      return (
        <li key={move}>
          <button
            onClick={() => this.jumpTo(move)}
            style={{ fontWeight: stepNumber === move ? "bold" : "" }}
          >
            {desc}
          </button>
        </li>
      );
    });

    let status;
    if (winner) {
      status = <span style={{ color: "red" }}>{"winner: " + winner}</span>;
    } else {
      if (stepNumber > 8) {
        status = <span style={{ color: "red" }}>平局</span>;
      } else {
        status = "next player: " + (this.state.xIsNext ? "X" : "O");
      }
    }

    return (
      <div className="game">
        <div className="game-board">
          <Board
            squares={current.squares}
            onClick={(i) => this.handleClick(i)}
            winnerSquares={winnerSquares}
          />
        </div>
        <div className="game-info">
          <div>{status}</div>
          <div>
            <span>排列：</span>
            <button onClick={() => this.sort()}>
              {ascend ? "升序" : "降序"}
            </button>
          </div>
          <ol reversed={ascend ? false : true}>
            {ascend ? moves : moves.reverse()}
          </ol>
        </div>
      </div>
    );
  }
}

// ========================================

ReactDOM.render(<Game />, document.getElementById("root"));

function calculateWinner(squares) {
  const lines = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6],
  ];
  for (let i = 0; i < lines.length; i++) {
    const [a, b, c] = lines[i];
    if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
      return lines[i];
    }
  }
  return [];
}
